#include "proc/cmdline.h"

void proc_cmdline_of_buffer(char* start_of_line, CmdLine *c) {
    char *t = LineTrim(start_of_line);
    for (int i = 0; i < sizeof(values) / sizeof(values[0]); i++) {
        if (LineStartWith(t, (char*)values[i])) {
            GSList *splitT = split_cnt(t, '=', 1);
            // g_slist_foreach(splitT, printf_iterator, "-->");
            switch (i) {
            case 0: strcpy(c->Model,        g_slist_nth(splitT, 1)->data); break;
            case 1: strcpy(c->Type,         g_slist_nth(splitT, 1)->data); break;
            case 2: strcpy(c->Hardversion,  g_slist_nth(splitT, 1)->data); break;
            case 3: strcpy(c->SN,           g_slist_nth(splitT, 1)->data); break;
            }
            g_slist_foreach(splitT, (GFunc)g_free, NULL);
            g_slist_free(splitT);
        }
    }
    free(t);
}

void proc_cmdline_printf_iterator(gpointer item, gpointer prefix) {
    GSList *temp = split_cnt((char*)item, '=', 1);
    if (g_slist_length(temp) == 2) {
        char *one = (char*)g_slist_nth(temp, 0)->data;
        char *two = (char*)g_slist_nth(temp, 1)->data;
        DEBUG_LOG("%s %s : %s", (char*)prefix, one, two);
    }
    GS_FREE(temp);
}

GSList * proc_cmdlineSplit(char *buf) {
    GSList *list = NULL;
    char *p = NULL;
    bool tag = false;
    char *end_of_word = NULL;

    if (buf == NULL) return NULL;

    char *buffer = createBufferCopy(buf);

    p = buffer + strlen(buffer);

    for(; p != buffer; p--) {
        if (*p == '=' && !tag) {
            tag = true;
            continue;
        }
        if (g_ascii_isspace(*p) && tag) {
            tag = false;
            list = g_slist_append(list, createBufferCopy(p+1));
            *p = 0;
            continue;
        }
    }

    if (tag) {
        list = g_slist_append(list, createBufferCopy(p));
    }

    return list;
}